package com.zoweunion.mechanic.netty;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.zoweunion.mechanic.service.base.NettyService;
import com.zoweunion.mechanic.util.ConverUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

@Component
@Sharable
public class DiscardServerHandler extends ChannelInboundHandlerAdapter{
	
	public static Map<String, String> map = new HashMap<String, String>();

	public static List<Map<String, String>> mapList = new ArrayList<Map<String,String>>();
    @Resource
    private NettyService nettyService;
       
    @Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		 try {
	            ByteBuf in = (ByteBuf) msg;
	            byte[] req=new byte[in.readableBytes()];
	            in.readBytes(req);
	            String body=new String(req,"GBK");
	            String aString=ConverUtil.byteArrToHexStr(req);
	            byte[] destIdBuffer = new byte[2];
				byte[] destDataBuffer = new byte[8];
				for (int i = 0; i < req.length/12; i++) {
					System.arraycopy(req, 4+12*i, destIdBuffer, 0, 2);
					System.arraycopy(req, 7+12*i, destDataBuffer, 0, 8);	
					String key = ConverUtil.byteArrToHexStr(destIdBuffer);
					String value = ConverUtil.byteArrToHexStr(destDataBuffer);
					map.put(key, value);			
				}
				mapList.add(map);
	            System.out.println("body:"+body+",响应次数:");
	            System.out.println("传输内容是");
	            System.out.println(mapList);
	            System.out.println(mapList.toString());
	            //这里调用service服务
	            nettyService.handle(); 
	            ctx.writeAndFlush("Received your message !\n");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}  finally {
	            ReferenceCountUtil.release(msg);
	        }
		
	}
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 出现异常就关闭
        cause.printStackTrace();
        ctx.close();
    }
	
	
	
}